package com.ly.hotel.spainterface.jg.view;

import android.app.DialogFragment;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

import com.google.gson.Gson;
import com.ly.hotel.R;
import com.ly.hotel.spainterface.jg.bean.Massage;
import com.ly.hotel.spainterface.jg.bean.MassageBean;
import com.ly.hotel.spainterface.jg.bean.MassageItem;
import com.ly.hotel.spainterface.jg.bean.gson.dbfile.DbWrite;
import com.ly.hotel.spainterface.jg.bean.gson.goods.Goods;
import com.ly.hotel.spainterface.jg.bean.gson.goods.GoodsResult;
import com.ly.hotel.spainterface.jg.bean.gson.postJson.GoodsPara;
import com.ly.hotel.spainterface.jg.utils.GsonUtils;
import com.ly.hotel.spainterface.jg.utils.OkHttpUtils;

import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by ThinkPad on 2018/3/2.
 */

public class CustomGoodsScanningDialog extends DialogFragment {

    private List<Massage> massageList;
    private String serverIP;
    private String serverPORT;
    private String cashierIp;
    private String cashierPort;
    private int[] judgeNum = {0,1};
    private List<MassageItem> massageItemList;
    private static int picNum = 0;
    private CustomLoadingDialog loadingDialog;
    private TextView scanningFinishTips;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    String jsonString = msg.obj.toString();
                    Log.d("GoodsHideDialog",jsonString);
                    if(msg.arg1 == judgeNum[1]) {
                        loadingDialog.close();
                        GoodsResult goodsResult = GsonUtils.parseSimpleJson(jsonString, GoodsResult.class);
                        if (goodsResult.isSuccess()) {
                            List<Goods> goodses = goodsResult.getResult().getLstGoods();
                            massageItemList = new ArrayList<>();
                            for (int i = 0; i < goodses.size(); i++) {
                                Goods goods = goodses.get(i);
                                MassageItem massageItem = new MassageItem();
                                massageItem.setId(goods.getGoodsId());
                                massageItem.setName(goods.getGoodsName());
                                massageItem.setUnit(goods.getUnit());
                                massageItem.setPrice(Double.parseDouble(goods.getPrice()));
                                massageItemList.add(massageItem);
                            }
                        }

                        if(massageItemList.size() > 0){
                            for(int i = 0;i < massageItemList.size();i ++){
                                MassageItem massageItem = massageItemList.get(i);
                                String massageItemId = massageItem.getId();
                                String massageItemName = massageItem.getName();
                                String imageUrl = "http://" + serverIP + ":" + serverPORT + "/upload/interface/consume/pic/" + massageItemId + ".jpg";
                                getImageResource(imageUrl,massageItemId,massageItemName);
                            }
                            scanningFinishTips.setVisibility(View.VISIBLE);
                        }
                    }else if(msg.arg1 == judgeNum[0]){
                        if(loadingDialog != null){
                            loadingDialog.close();
                        }
                        DbWrite dbWrite = GsonUtils.parseSimpleJson(jsonString, DbWrite.class);
                        if(dbWrite.getCode() == 200){
                            picNum ++;
                            Log.d("GoodsHideDialog",picNum + "");
                            //Toast.makeText(getContext(),"扫描图片成功！",Toast.LENGTH_SHORT).show();
                        }else{
                            //Toast.makeText(getContext(),"扫描图片失败！",Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;

                case 2:
                    if(loadingDialog != null){
                        loadingDialog.close();
                    }
                    break;
            }
        }
    };

    @Override
    public void onStart() {
        super.onStart();
        Window window = getDialog().getWindow();
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.windowAnimations = R.style.customDialogAnim;
        window.setAttributes(layoutParams);
    }

    @Override
    public View onCreateView(LayoutInflater inflater,  ViewGroup container, Bundle savedInstanceState) {
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);

        Bundle bundle = getArguments();
        MassageBean massageBean = (MassageBean) bundle.getSerializable("massageBean");
        massageList = massageBean.getMassageList();
        serverIP = bundle.getString("serverIP","");
        serverPORT = bundle.getString("serverPORT","");
        cashierIp = bundle.getString("cashierIP","");
        cashierPort = bundle.getString("cashierPORT","");

        View view = inflater.inflate(R.layout.jg_goods_scanning_pic_layout,container,false);
        ImageButton goodsScanningClose = (ImageButton) view.findViewById(R.id.goods_scanning_close);
        Button startScanningPic = (Button) view.findViewById(R.id.start_scanning_pic);
        scanningFinishTips = (TextView) view.findViewById(R.id.scanning_finish_tips);
        goodsScanningClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

        startScanningPic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadingDialog = new CustomLoadingDialog(getActivity(),"扫描图片中...");
                loadingDialog.show();
                if(massageList.size() > 0){
                    for(int i = 0;i < massageList.size();i ++){
                        getGoods(massageList.get(i).getId());
                    }
                }
            }
        });
        return view;
    }

    public void getGoods(String CatalogId){
        Map<String,String> map = new HashMap<>();
        map.put("CatalogId",CatalogId);
        GoodsPara goodsPara = new GoodsPara();
        goodsPara.setCatalogId(CatalogId);
        Gson gson = new Gson();
        String jsonString = gson.toJson(goodsPara);// 提交的json数据
        String url = "http://" + cashierIp + ":" + cashierPort + "/TsInterface/Ts_GetGoods";
        OkHttpUtils.getInstance().postJsonResource(jsonString,url,handler,judgeNum[1]);
    }

    // 请求图片资源
    public void getImageResource(final String imageUrl, final String massageItemId, final String massageItemName){
        new Thread(new Runnable() {
            @Override
            public void run() {
                InputStream is = OkHttpUtils.getInstance().getImageResource(imageUrl);
                if(is == null){
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append(massageItemId + "-" + massageItemName + "\r\n");
                    //String content = massageItemId + "-" + massageItemName + "\r\n";
                    Log.d("GoodsHideDialog",massageItemId + "*********" + massageItemName);
                    String content = "";
                    try {
                        content = URLEncoder.encode(stringBuilder.toString(),"UTF-8");
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    String url = "http://" + serverIP + ":" + serverPORT + "/api/dbfile-write.json?filename=JGConsumePic.txt&content=" + content + "&isappend=true";
                    OkHttpUtils.getInstance().getTextResource(url,handler,judgeNum[0]);
                }
            }
        }).start();
    }
}
